<?php
namespace Models;
class PostModel extends CommonModel {

    public function add ($data) {
        $sql = 'insert into posts(title, content, cate_id, user_id) values
                (:title, :content, :cate_id, :user_id)';
        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':title', $data['title']);
        $stmt->bindValue(':content', $data['content']);
        $stmt->bindValue(':user_id', $data['user_id']);
        $stmt->bindValue(':cate_id', $data['cate_id']);
        return $stmt->execute();
    }


    public function getPosts($where = '', $limit = '') {
        $sql = 'select posts.id, posts.title as p_title, posts.content, posts.praise_count, posts.step_count, posts.created_at, categoies.title as c_title, users.username from posts
                left join categoies on posts.cate_id = categoies.id
                left join users on posts.user_id = users.id';
        if (!empty($where)) $sql = $sql . $where;
        $sql .= ' order by posts.id desc';
        if (!empty($limit)) $sql .= $limit;
        return $this->db->query($sql)->fetchAll();
    }

    public function getPostCount($where = '') {
        $sql = 'select count(id) as count from posts';
        if (!empty($where)) $sql = $sql . $where;
        return $this->db->query($sql)->fetch()['count'];
    }
}